const EggService = require('egg').Service
const dayjs = require('dayjs')

class Service extends EggService {
  /**
   * 发送短信
   */
  async send(options) {
    const { ctx } = this
    const { juhe } = this.app
    const { config } = this
    const { mobile, type, duration, session } = options

    this.ctx.helper.validate(options, {
      required: ['mobile', 'type'],
    })

    let code = '123456'

    // let code
    // const templateId = config.juhe.sendSms[type]
    // if (!templateId) throw '缺少模板ID'

    // if (config.superMobile && config.superMobile.indexOf(mobile) != -1) {
    //   code = '123456'
    // } else {
    //   code = Math.random().toString().substr(2, 6)

    //   await juhe.sendSms({
    //     mobile,
    //     templateId,
    //     data: {
    //       code,
    //     },
    //   })
    // }

    // 过期时间（5分钟）
    const expires = Date.now() + (duration || 1000 * 60 * 5)
    const captcha = {
      type,
      code,
      mobile,
      expires: dayjs(expires).unix(),
    }

    const doc = await this.ctx.model.Sms.create({
      type,
      code,
      mobile,
      expireTime: dayjs(expires).format('YYYY-MM-DD HH:mm:ss'),
    })

    if (session) {
      captcha.expires = dayjs(expires).unix()
      session.captcha = captcha
    }

    // 将老验证码设置为过期
    await ctx.model.Sms.updateOne(
      {
        _id: {
          $ne: doc._id,
        },
        mobile,
        status: 0,
      },
      {
        status: 2,
      }
    )

    return captcha
  }

  /**
   * 确认验证码
   * @param {*} options
   */
  async confirmCode(options) {
    const { ctx } = this

    ctx.helper.validate(options, {
      required: ['mobile', 'code', 'type'],
    })

    const { mobile, code, type } = options
    const now = dayjs().format('YYYY-MM-DD HH:mm:ss')

    const codeInfo = await this.ctx.model.Sms.findOne({
      mobile,
      code,
      type,
      status: 0,
      // 过期时间需要大于当前时间
      expireTime: {
        $gt: now,
      },
    }).sort({
      id: 'DESC',
    })

    if (!codeInfo) throw '无效验证码'

    codeInfo.status = 1
    await codeInfo.save()

    return codeInfo
  }
}

module.exports = Service
